package com.cmy.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

public class FileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取下载文件的路径
        String realPath = "E:\\learnJava\\JavaWeb\\JavaWeb-04-Servlet\\response\\src\\main\\resources\\akali.jpg";
        System.out.println("下载的路径:"+realPath);
        //下载的文件名
        String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
        //设法让浏览器支持下载,文件名为中文(不推荐中文)则+fileName--->+URLEncoder.encode(fileName,"UTF-8")
        resp.setHeader("Content-Disposition","attachment;filename="+fileName);
        //获取下载文件的输入流
        FileInputStream fis = new FileInputStream(realPath);
        //创建缓冲区
        int len;
        byte[] buffer = new byte[1024];
        //获取OutputStream对象
        ServletOutputStream os = resp.getOutputStream();
        //将FileOutputStream流写入到缓冲区,使用OutputStream将缓冲区中的数据输出到客户端
        while((len=fis.read(buffer))!=-1){
            os.write(buffer,0,len);
        }

        fis.close();
        os.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

    